package br.com.fogas.medicao.thread;

import android.util.Log;
import br.com.fogas.medicao.activity.ConcluirSimulNotaActivity;
import br.com.fogas.medicao.application.Constants;

public class AutorizarNotaOnlineCronometroThread extends Thread {
	
	private ConcluirSimulNotaActivity activity;
	
	private ThreadEventListener listener;

	public AutorizarNotaOnlineCronometroThread(ConcluirSimulNotaActivity activity, ThreadEventListener listener) {
		this.activity = activity;
		this.listener = listener;
		this.setName("CronometroThread");
		this.setDaemon(true);
	}

	@Override
	public void run() {
		try {
			Log.d(Constants.AUTORIZACAO_NOTA, "iniciando cronometro");
			while (activity.getSegundosEsperaAutorizacao() >= 0) {
				if(isInterrupted()) {
					Log.d(Constants.AUTORIZACAO_NOTA, "nota processada primeiro, cronometro encerrado!");
					break;
				} else {
					String tempo = timeConversion(activity.getSegundosEsperaAutorizacao());
					Log.d(Constants.AUTORIZACAO_NOTA, "cronometro "+tempo);
					activity.atualizarCronometro(tempo);
					Thread.sleep(1000);
				}	
			}
			
			if(!isInterrupted()) {
				Log.d(Constants.AUTORIZACAO_NOTA, "cronometro encerrado, tempo de espera estourado!");
				listener.threadComplete(this, null);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	private String timeConversion(int seconds) {
	    final int MINUTES_IN_AN_HOUR = 60;
	    final int SECONDS_IN_A_MINUTE = 60;

	    int minutes = seconds / SECONDS_IN_A_MINUTE;
	    seconds -= minutes * SECONDS_IN_A_MINUTE;

	    int hours = minutes / MINUTES_IN_AN_HOUR;
	    minutes -= hours * MINUTES_IN_AN_HOUR;
	    
	    String hoursStr = (hours < 10) ? "0"+String.valueOf(hours) : String.valueOf(hours);
	    String minutesStr = (minutes < 10) ? "0"+String.valueOf(minutes) : String.valueOf(minutes);
	    String secondsStr = (seconds < 10) ? "0"+String.valueOf(seconds) : String.valueOf(seconds);
	    return "- " +hoursStr + ":" + minutesStr + ":" + secondsStr;
	}
}